/**
 * Created by 55456 on 2016/4/10.
 */
var db = require("../models/index");
var User = db.models.User;
var Story = db.models.Story;
var appConfig = require("../configs/appConfig");
var getStoryByUserID = function * (id,isOwn,page,count){
    var whereObj = isOwn ? {AuthorID:id} : {AuthorID:id,publicEnable:1};
    var stories = yield Story.findAll({
        where:whereObj,
        order:[["updatedAt","DESC"]],
        offset:(page - 1) * count,
        limit:count,
        include:[{
            model:User,
            attributes: { exclude: ["password"] },
            through:{
                where:{
                    isLike:1
                }
            }
        }]
    });
    getStoriesLikeCount(stories);
    return stories;
};

var getStoryByStoryID = function *(id){
    var story = yield Story.findOne({
        where:{
            id:id
        },
        include:[{
            model:User,
            attributes: { exclude: ["password"] },
            through:{
                where:{
                    isLike:1
                }
            }
        }]
    });
    getStoryLikeCount(story);
    return story;
};

var AddStory = function *(story){
    var h5Url = appConfig.h5Url + story.id;
    return {id:story.id,url:h5Url};
};

var getStoriesLikeCount = (stories) =>{
    for(var x in stories){
        stories[x].dataValues.likeCount = stories[x].Users.length;
    }
};

var  getStoryLikeCount = (story) => {
    story.dataValues.likeCount = story.Users.length;
};

var getAllPublicStories = function *(page,count,timestamps){
    var stories = yield Story.findAll({
        where:{
            createdAt:{
                $lte:timestamps.toString()
            },
            publicEnable:1
        },
        order:[["createdAt","DESC"]],
        offset:(page - 1) * count,
        limit:count,
        include:[{
            model:User,
            attributes: { exclude: ["password"] },
            through:{
                where:{
                    isLike:1
                }
            }
        }]
    });
    getStoriesLikeCount(stories);
    return stories;
};

module.exports = {
    getStoryByUserID,
    getStoryByStoryID,
    AddStory,
    getAllPublicStories
};